package com.mindpointeye.websockt.javawebsocket

import com.demon.logger.Logger
import com.mindpointeye.websockt.IWebSocketListener
import com.mindpointeye.websockt.IWebSocketManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.java_websocket.client.WebSocketClient
import org.java_websocket.enums.ReadyState
import timber.log.Timber
import java.net.URI
import java.util.*
import kotlin.concurrent.timerTask

/**
 * 类简要描述
 * <p/>
 * <p>
 * 类详细描述
 * </p>
 *
 * @author zhaozeyang
 * @date 2/2/21
 */
enum class JavaWebSocketManager : IWebSocketManager {

    INSTANCE {
        private val TAG = "JavaWebSocketManager"

        private var mClient: WebSocketClient? = null

        private lateinit var mUrl: String

        override fun createSocketClient(url: String, listener: IWebSocketListener?) {
            mUrl = url
            mClient = JavaWebSocketClient(URI.create(url), listener)
            connect()
        }

        override fun connect() {
            GlobalScope.launch(Dispatchers.IO) {
                try {
                    mClient?.connectBlocking()
                } catch (e: Exception) {
                    Logger.e(TAG, "connect failed ", e)
                }
            }
        }

        override fun closeConnect() {
            try {
                mClient?.close()
            } catch (e: Exception) {
                Logger.e(TAG, "closeConnect failed ", e)
            } finally {
                mClient = null
            }
        }

        override fun sendMessage(msg: String) {
            if (mClient?.readyState?.equals(ReadyState.OPEN) == true) {
                try {
                    mClient?.send(msg)
                }catch (e:Exception){
                    e.message?.let { Logger.d(TAG, it) }
                }
            } else {
                Logger.d("socket状态", mClient?.readyState.toString())
            }
        }

        override fun sendMessage(msg: ByteArray?) {
            mClient?.send(msg)
        }

        override fun isClosed(): Boolean {
            //为null时返回true
            return mClient?.isClosed ?: true
        }

        var lockReconnect = false   //避免重复连接

        override fun reconnect() {

            if (lockReconnect) {
                return
            }
            lockReconnect = true
            Timer().schedule(timerTask {
                if (null == mClient) {
                    createSocketClient(mUrl)
                } else {
                    if (mClient!!.isClosed) {
                        performReconnect()
                        Timber.tag("reconnect").e("心跳包检测重连")
                    }
                }
            }, 0, 2000) //改为2秒
        }

        private fun performReconnect() {
            GlobalScope.launch(Dispatchers.IO) {
                try {
                    Timber.tag("performReconnect").i("isOpen：${mClient?.reconnectBlocking()}")
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
}